/*
 * Copyright 2024 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.permission.service.impl;

import com.lap.permission.cachekey.DictKey;
import com.lap.permission.dal.DictDetailDAO;
import com.lap.permission.domain.entity.DictDetail;
import com.lap.permission.manager.DictDetailManager;
import com.lap.permission.service.DictDetailService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class DictDetailServiceImpl implements DictDetailService {

    private final DictDetailDAO dictDetailDAO;

    private final DictDetailManager dictDetailManager;

    @Cacheable(value = DictKey.DETAIL_CODE, key = "#dictCode+':'+#detailValue+':'+#lang", unless = "#result==null")
    @Override
    public DictDetail queryByDictCode(String dictCode, Integer detailValue, String lang) {
        return dictDetailDAO.queryByDictCode(dictCode, detailValue, lang);
    }

    @Cacheable(value = DictKey.DETAIL_CODES, key = "#dictCodes+':'+#lang", unless = "#result.isEmpty()")
    @Override
    public Map<String, List<DictDetail>> queryByDictCodes(List<String> dictCodes, String lang) {
        if (CollectionUtils.isEmpty(dictCodes)) {
            return Collections.emptyMap();
        }

        List<DictDetail> dataList = dictDetailDAO.queryByDictCodes(dictCodes, lang);
        Map<String, List<DictDetail>> result = dataList.stream().collect(Collectors.groupingBy(DictDetail::getDictCode));

        result.forEach((key, value) -> value.sort(Comparator.comparingInt(DictDetail::getOrders)));
        return result;
    }

    @Override
    public List<DictDetail> queryByDictId(Integer dictId) {
        return dictDetailDAO.queryByDictId(dictId);
    }

    @CacheEvict(value = {DictKey.DETAIL_CODES, DictKey.DETAIL_CODE}, allEntries = true)
    @Override
    public Integer insertDictDetail(Integer dictId, List<DictDetail> dataList) {
        return dictDetailManager.insertDictDetail(dictId, dataList);
    }

}
